// pages/carteShow.js
import {
  baseUrl,
  ftp_share_image,
  get_carte,
  get_headerimg,
  get_open_id,
  update_coll_status,
  update_flag_like_status,
  update_like_status,
  update_scan,
  update_user_invite,
  user_login
} from "../../utils/api.js";


const app = getApp()
let innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = false
var showShareStatus = 0;
var share_uid = 0;
var add_invitestatus = false;

Page({
  /**
   * 页面的初始数据
   */

  data: {
    TaskShow: 0, //默认0 ，用户授权 1 ，分享 2
    fxTaskShow: 0,
    haveTap: 1, // 1: 可以点击 0：不可点击
    haveShare: 0, // 0：完成/未开始 1：分享
    phoneShow: 0,
    openid: '',
    phone: '',
    code: '',
    codePlace: '获取验证码',
    setInter: '',
    durations: 0,
    playStatus: false,
    systemInfo: {},
    content: '',
    carte_id: '',
    issharecome: false,
    uid: '',
    Goods: [],
    priceList: [],
    integralpriceList: [],
    goodsCount: 0,
    aplay: false,
    controls: true,
    isFolded: false,
    sellerList1: [],
    video_show: true,
    userinfoShow: false,
    authSettingUser: 1,
    autotrue: true,
    authSettingUser_task: true,
    video1_show: true,
    fangwname: '',
    fx_mode: false, //分享遮罩
    liulanList: [],
    iconArr: [{
        src: '../../images/ic_connection_share_weixin.png',
        text: '微信'
      },
      {
        src: '../../images/ic_connection_share_haibao.png',
        text: '海报'
      }
    ],
    labels: []


  },
  hiden_task: function() {

    this.setData({
      authSettingUser_task: true,

    });
  },
  no_share: function() {
    wx.showModal({
      title: '提示',
      content: '名片信息未审核，请联系客服',
    })
  },
  // 展开更多
  change: function(e) {
    // this.setData({
    //   isFolded: !this.data.isFolded,
    // })
    this.setData({
      isFolded: false,
    })
  },

  formSubmit(e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },
  // 点击更多去个人商城
  bindMyMall: function(e) {
    if (this.data.food_mall > 0) {
      wx.navigateTo({
        url: '/shopPages/shopxq/shopxq?mid=' + e.currentTarget.dataset.vid,

      })
    } else {
      wx.navigateTo({
        // url: '../myMall/myMall?mid=' + e.currentTarget.dataset.vid,
        url: '/shopPages/personalShop/personalShop?mid=' + e.currentTarget.dataset.vid,
      })
    }
  },
  //点击进入个人官网
  jumpGw: function(e) {
    wx.navigateTo({
      url: '../website/website',
    })
    app.globalData.SwitchTabParams.v_id = e.currentTarget.dataset.vid
    console.log(app.globalData.SwitchTabParams.v_id);
    if (e.currentTarget.dataset.v_id != app.globalData.userInfo.id) {
      app.addlog(e.currentTarget.dataset.v_id, this.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 7, '')
    }

  },

  //点击进入详情页面
  bindGoodsTap: function(e) {
    var id = e.detail.button_typId;
    var title = e.detail.button_status;
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?id=' + id + '&title=' + title,
    })
  },
  // 点击进去名片夹
  bindCardTap: function(e) {
    wx.navigateTo({
      url: '../carteFavorites/carteFavorites',
    })
    this.setData({
      TaskShow: 0
    })
  },
  // 点击进去咨询页面
  bindGoSocksTap: function(e) {
    var that = this
    this.setData({
      TaskShow: 0
    })
    wx.navigateTo({
      url: '../socks/socks?socksuid=' + app.globalData.SwitchTabParams.v_id,
    })
    app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 6, '')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu()
    const that = this
    this.setData({
      options
    })
    if (app.globalData.SwitchTabParams.v_id) {
      that.setData({
        carte_id: app.globalData.SwitchTabParams.v_id
      })
    } else {
      that.setData({
        carte_id: 191
      })
    }
    if (JSON.stringify(options) != '{}') {
      let changed = new Object()

      if (options.scene) {
        console.log(22);
        let scene = decodeURIComponent(options.scene);
        //&是我们定义的参数链接方式
        changed['issharecome'] = true
        changed['carte_id'] = options.scene.split("-")[1];
        app.globalData.shareOptions = {
          carte_id: options.scene.split("-")[1],
          share_id: options.scene.split("-")[0]
        }
        share_uid = options.scene.split("-")[0];
        app.globalData.SwitchTabParams = {
          v_id: options.scene.split("-")[1]
        }
      } else if (options && options.share_id) {
        share_uid = options.share_id
        changed['issharecome'] = true
        changed['carte_id'] = options.carte_id
        app.globalData.shareOptions = JSON.parse(JSON.stringify(options)) // share_id = invite_id 分享时才有
        app.globalData.SwitchTabParams.v_id = options.carte_id;
      } else {
        share_uid = 0
        app.globalData.shareOptions = {
          carte_id: '',
          share_id: ''
        }
      }
      app.globalData.share_uid = share_uid;
      // console.log(app.globalData.shareOptions);
      that.setData(changed)
    }
    add_invitestatus = true;
    // that.checkUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  carnum: function(uid) {
    var that = this;
    var url2 = '/cart/index';
    var params2 = {
      uid: uid,
      // mg_uid: app.globalData.SwitchTabParams.v_id
    };
    app.HttpGetSend(url2, params2, function(res) {
      // console.log(res);
      if (result_data === '-10000') {
        wx.hideTabBar()
        that.setData({
          authSettingUser: 0
        });
      }
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
        that.setData({
          goodsList: []
        })
      } else {
        var lists = [];
        if (res.data) {


          for (let i in res.data) {
            var obj = {};
            obj = res.data[i];
            var goods_list = res.data[i].goods_list;
            var goodsSum = 0;
            for (let j = 0; j < goods_list.length; j++) {
              goodsSum += goods_list[j].num * goods_list[j].price;
              goods_list[j].checked = false;
              if (goods_list[j].num == 1) {
                goods_list[j].noJian = true;
              } else {
                goods_list[j].noJian = false;
              }
            }
            obj.goodsSum = goodsSum;
            obj.checked = false;
            lists.push(obj);
            var count = lists.length;
            count = count + '';
            wx.setTabBarBadge({
              index: 2,
              text: count
            })
          }
        } else {
          wx.removeTabBarBadge({
            index: 2,
          })
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    var uid = that.data.carte_id;
    // setInterval(function(){that.carnum(uid)},1000);
    if (app.globalData.SwitchTabParams.v_id) {
      that.setData({
        carte_id: app.globalData.SwitchTabParams.v_id
      })
    } else {
      that.setData({
        carte_id: 191
      })
    }
    that.setData({
      video1_show: true
    })
    if (!showShareStatus) {
      that.checkUserInfo()
    }


    var url2 = "/cardshop_api/card_word";
    var params2 = {
      type: 3,
      uid: app.globalData.SwitchTabParams.v_id
    }
    app.HttpPostSend(url2, params2,
      function(result_data) {
        if (result_data === '-10000') {
          that.setData({
            authSettingUser: 0
          });
          wx.hideTabBar()
        }
        if (result_data.msg != "success") {
          app.showTipMsg(result_data.msg);
        } else {

          if (!!result_data.data) {
            that.setData({
              content: result_data.data.content


            })

          }
        }
      })

    if (showShareStatus > 0) {
      that.setData({
        fxTaskShow: 1
      });
    }
  },

  changeStatus: function() {
    showShareStatus = 0;
    this.setData({
      fxTaskShow: 0
    });
  },

  // 检测是否需要登录
  checkUserInfo: function() {
    const that = this
    let openid = wx.getStorageSync('openid')
    console.log(openid);
    if (openid) {
      app.globalData.openid = openid
      that.setData({
        openid,
      })
      let url = '/user_api/getInfoByOpenID';
      app.HttpPostSend(
        url, {
          openid: openid,
          invite_id: share_uid,
        },
        function(result_data) {

          if (result_data === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
            return false;
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            if (!!result_data.data) { //如果后台有数据
              app.globalData.userInfo = {
                ...result_data.data
              }
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify({
                  ...result_data.data
                })
              })
              that.setData({
                haveTap: 1,
                userInfo: result_data.data,
                u_id: app.globalData.userInfo.id
              })
              add_invitestatus = false;
              // app.update_cart(app.globalData.userInfo.id);
              that.getCarteInfo(app.globalData.userInfo.id)
              that.getHeaderList();
              // that.getCardWord()
              if (that.data.issharecome == true) {
                that.setData({
                  TaskShow: 3
                })
              }
              try {
                // ai添加纪录 对我感兴趣
                app.aiAddRecord(1)
              } catch (error) {
                console.log(error)
              }
            } else { //如果后台无数据
              wx.login({
                success(res) {
                  let params = {
                    code: res.code
                  }
                  app.HttpGetSend(get_open_id, params, function(result) {
                    if (result.msg != "success") {
                      app.showTipMsg(result.msg);
                    } else {
                      app.globalData.openid = result.data.openid.openid;
                      // app.globalData.userInfo = result.data.userinfo;
                      // that.getCarteInfo(app.globalData.userInfo.id)
                      // app.update_cart(result.data.userinfo.id);
                      wx.setStorage({
                        key: 'openid',
                        data: result.data.openid.openid
                      })
                      that.setData({
                        openid: result.data.openid.openid
                      })
                      that.setData({
                        TaskShow: 1,
                        openid: result.data.openid.openid
                      })
                    }
                  }, 1)
                }
              })
            }
          }
        })
    } else {

      wx.login({
        success(res) {
          let params = {
            code: res.code,
            invite_id: share_uid,
          }
          app.HttpGetSend(get_open_id, params, function(result) {

            if (result.msg != "success") {
              app.showTipMsg(result.msg);
            } else {
              app.globalData.userInfo = result.data.userinfo;
              console.log(app.globalData.userInfo);
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify(result.data.userinfo)
              })
              that.setData({
                haveTap: 1,
                userInfo: result.data.userinfo,
                u_id: app.globalData.userInfo.id
              })
              add_invitestatus = false;
              // app.update_cart(app.globalData.userInfo.id);
              that.getCarteInfo(app.globalData.userInfo.id)
              that.getHeaderList();

              // that.getCardWord()
              if (that.data.issharecome == true) {
                that.setData({
                  TaskShow: 3
                })
              }
              try {
                // ai添加纪录 对我感兴趣
                app.aiAddRecord(1)
              } catch (error) {
                console.log(error)
              }
              // app.globalData.openid = result.data.openid.openid;
              // // app.globalData.userInfo = result.data.userinfo;
              // // that.getCarteInfo(app.globalData.userInfo.id)
              // // app.update_cart(result.data.userinfo.id);
              // wx.setStorage({
              //   key: 'openid',
              //   data: result.data.openid.openid
              // })
              // that.setData({
              //   openid: result.data.openid.openid
              // })
              // that.setData({
              //   TaskShow: 1,
              //   openid: result.data.openid.openid
              // })
            }
          }, 1)
        },
        fail: function(res) {
          console.log('失败');
        }
      })
    }
    let systemInfo = wx.getSystemInfoSync()
    app.globalData.systemInfo = systemInfo
    this.setData({
      systemInfo
    })
  },

  // 获取用户信息
  bindGetUserInfo: function(e) {

    const that = this
    if (e.detail.errMsg == "getUserInfo:ok") {
      wx.showTabBar()
      that.setData({
        authSettingUser: 1
      });
    } else {
      wx.hideTabBar()
    }
    let userInfo = e.detail.userInfo
    try {
      app.HttpPostSend(
        user_login, {
          openid: app.globalData.openid,
          username: userInfo.nickName,
          // phone: that.data.phone,
          // code: that.data.code,
          logo: userInfo.avatarUrl,
          sex: userInfo.gender,
          invite_id: share_uid,
        },
        function(result_data) {


          if (result_data === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
          }
          if (result_data.msg != "success") {
            app.showTipMsg(result_data.msg);
          } else {
            let userInfo = {
              ...result_data.data
            }
            app.globalData.userInfo = userInfo
            wx.setStorage({
              key: 'userInfo',
              data: JSON.stringify(userInfo)
            })
            that.setData({
              TaskShow: 0,
              haveTap: 1,
              userInfo: userInfo
            })
            that.getCarteInfo(userInfo.id)
            that.getHeaderList();
            add_invitestatus = false;
            if (that.data.issharecome == true) {
              that.setData({
                TaskShow: 3
              })
            }
            try {
              // ai添加纪录 对我感兴趣
              app.aiAddRecord(1)
            } catch (error) {
              console.log(error)
            }
          }
        })
    } catch (error) {

    }
  },

  //获取浏览头像列表

  getHeaderList: function() {

    const that = this
    var carte_id = that.data.carte_id
    app.HttpGetSend(get_headerimg, {
        uid: carte_id,
      },
      function(res) {
        // console.log(res)
        if (res === '-10000') {
          wx.hideTabBar()
          that.setData({
            authSettingUser: 0
          });
        }
        if (res.msg != "success") {
          app.showTipMsg(res.msg);
        } else {
          // console.log(res)
          var list = [];
          for (var i = 0; i < res.data.length; i++) {
            list.push(res.data[i]);
          }
          // console.log(list)
          that.setData({
            liulanList: list
          })
        }
      })
  },

  // 获取名片信息
  getCarteInfo: function(u_id) {
    const that = this
    if (u_id > 0) {
      if (!showShareStatus) {
        // wx.showLoading({
        //   title: '正在加载',
        // })
      }


      var carte_id = that.data.carte_id

      try {
        if (that.data.options && that.data.options.carte_id) {
          let update_user_invite_params = {
            uid: that.data.options.carte_id,
            invite_id: that.data.userInfo.id,
            source_id: that.data.options.share_id
          }
          console.log('推荐参数:', update_user_invite_params);
          app.HttpPostSend(update_user_invite, update_user_invite_params, function(res) {
            if (res === '-10000') {
              wx.hideTabBar()
              that.setData({
                authSettingUser: 0
              });
            }
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              console.log('统计推荐数量:', res.data);
            }
          });
        }
        // 增加浏览次数
        app.HttpGetSend(
          update_scan, {
            uid: carte_id,
            browse_id: app.globalData.userInfo.id
          },
          function(res) {
            // console.log(res)
            if (res === '-10000') {
              wx.hideTabBar()
              that.setData({
                authSettingUser: 0
              });
            }
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {

            }
          })
        if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {
          // 发送模板消息-访客到访通知
          app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter?coming_status=1', '正在访问门店帮扶系统', '', '', '')

          // 雷达添加查看记录
          app.radarAdd(carte_id, 5, '', '', app.globalData.userInfo.logo)
        }
        // 获取名片信息
        app.HttpGetSend(get_carte, {
            uid: carte_id,
            v_id: u_id
          },
          function(res) {
            if (res === '-10000') {
              wx.hideTabBar()
              that.setData({
                authSettingUser: 0
              });
            }
            wx.hideLoading();
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              that.setData({
                com_lat: res.data.latitude,
                com_lng: res.data.longitude,
                address: res.data.address,
                other: res.data.other,
                web: res.data.web_data,
                // banner: res.data.web_data,
                food_mall: res.data.food_mall,
                fangwname: res.data.name
              });
              if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {
                // 发送模板消息-访客到访通知
                app.addlog(app.globalData.SwitchTabParams.v_id, res.data.name, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 5, '')
              }
              let checkNullEmpty = (aim) => {
                if (aim != '' && aim != null) {
                  return true
                } else {
                  return false
                }
              }
              // 名片信息
              let CarteInfo = new Object()
              CarteInfo.id = res.data.id
              CarteInfo.examine_status = res.data.examine_status
              CarteInfo.is_allow = res.data.is_allow
              // 名片 形象照
              CarteInfo.img = new Object()
              CarteInfo.img = {
                type: 0,
                src: '../../images/img_block.png'
              }
              if (checkNullEmpty(res.data.img)) {
                CarteInfo.img = {
                  type: 1,
                  src: res.data.img
                }
              }
              // 名片 公司名
              CarteInfo.comName = new Object()
              CarteInfo.comName = {
                type: 0,
                content: '公司'
              }
              if (checkNullEmpty(res.data.company)) {
                CarteInfo.comName = {
                  type: 1,
                  content: res.data.company
                }
              }
              // 名片 公司logo
              CarteInfo.comLogo = new Object()
              CarteInfo.comLogo = {
                type: 0,
                src: '../../images/carteFavorites/logo_block.png'
              }
              if (checkNullEmpty(res.data.com_logo)) {
                CarteInfo.comLogo = {
                  type: 1,
                  src: res.data.com_logo
                }
              }
              // 名片 职业
              CarteInfo.position = new Object()
              CarteInfo.position = {
                type: 0,
                content: '职业'
              }
              if (checkNullEmpty(res.data.position)) {
                CarteInfo.position = {
                  type: 1,
                  content: res.data.position
                }
              }
              // 名片 名字
              CarteInfo.name = new Object()
              CarteInfo.name = {
                type: 0,
                content: '名字'
              }
              if (checkNullEmpty(res.data.name)) {
                CarteInfo.name = {
                  type: 1,
                  content: res.data.name
                }
              }
              // 名片 手机号
              CarteInfo.mobile = new Object()
              CarteInfo.mobile = {
                type: 0,
                content: '手机号'
              }
              if (checkNullEmpty(res.data.mobile)) {
                CarteInfo.mobile = {
                  type: 1,
                  content: res.data.mobile
                }
              }
              // 名片 邮箱
              CarteInfo.email = new Object()
              CarteInfo.email = {
                type: 0,
                content: '邮箱'
              }
              if (checkNullEmpty(res.data.email)) {
                CarteInfo.email = {
                  type: 1,
                  content: res.data.email
                }
              }
              // 名片 地址
              CarteInfo.address = new Object()
              CarteInfo.address = {
                type: 0,
                content: '地址'
              }
              if (checkNullEmpty(res.data.address)) {
                CarteInfo.address = {
                  type: 1,
                  content: res.data.address
                }
              }

              // console.log(CarteInfo)
              that.setData({
                CarteInfo
              })
              app.globalData.CarteInfo = CarteInfo
              // 点赞统计
              let VotesList = [{
                  type: 1,
                  icon: '../../images/carteShow/sign.png',
                  count: 0,
                  content: '人次浏览'
                },
                {
                  type: 2,
                  icon: '../../images/ic_connection_collect_nor.png',
                  status: 0,
                  count: 0,
                  content: '人收藏'
                },
                {
                  type: 3,
                  icon: '../../images/ic_connection_praise_nor.png',
                  status: 0,
                  count: 0,
                  content: '人点赞'
                }
              ]
              VotesList[0].count = res.data.browse_num
              VotesList[1].count = res.data.collection_num
              if (res.data.is_collection) {
                if (res.data.is_collection == 1) {
                  VotesList[1].status = res.data.is_collection
                  VotesList[1].icon = '../../images/ic_connection_collect_sel.png'
                }
              }
              VotesList[2].count = res.data.point_num
              if (res.data.is_point) {
                if (res.data.is_point == 1) {
                  VotesList[2].status = res.data.is_point
                  VotesList[2].icon = '../../images/ic_connection_praise_sel.png'
                }
              }
              // console.log(VotesList)
              that.setData({
                VotesList
              })

              // 联系列表
              let ContactList = []
              if (res.data.mobile) {
                let obj = {};
                obj.type = 1;
                obj.icon = '../../images/carteShow/phone_full.svg';
                obj.title = '拨打电话';
                obj.content = res.data.mobile;
                ContactList.push(obj);
              }
              if (res.data.weixin) {
                let obj = {};
                obj.type = 2;
                obj.icon = '../../images/carteShow/wechat.svg';
                obj.title = '加我微信';
                obj.content = res.data.weixin;
                ContactList.push(obj);
              }
              if (res.data.email) {
                let obj = {};
                obj.type = 3;
                obj.icon = '../../images/carteShow/email_full.svg';
                obj.title = '邮箱地址';
                obj.content = res.data.email;
                ContactList.push(obj);
              }
              if (res.data.address) {
                let obj = {};
                obj.type = 4;
                obj.icon = '../../images/carteShow/map.svg';
                obj.title = '地址';
                obj.content = res.data.address;
                ContactList.push(obj);
              }
              // console.log(ContactList)
              that.setData({
                ContactList
              })

              // 个人商城
              // let Goods = {
              //   type: 0,
              //   picture: '../../images/carteShow/noGoods.png'
              // }
              // if (res.data.goods && Object.keys(res.data.goods).length > 0) {
              //   Goods.type = 1
              //   Goods = {
              //     ...Goods,
              //     ...res.data.goods
              //   }
              // }

              // var labels = res.data.goods[0].label.split(',');

              console.log(res.data.goods);




              that.setData({
                Goods: res.data.goods
                // labels:labels
              });
              var list = [];
              var list1 = [];
              console.log(that.data.Goods)
              for (let i in that.data.Goods) {

                if (parseFloat(that.data.Goods[i].price) > parseFloat(that.data.Goods[i].integral_price)) {
                  console.log("============================-----------------------");
                  var temp = that.data.Goods[i].integral_price;
                  var price = Math.round((parseFloat(that.data.Goods[i].price) - parseFloat(that.data.Goods[i].integral_price)) * 100) / 100;
                  list.push(price);
                  list1.push(temp);


                  // that.data.Goods.price = Math.round((parseFloat(that.data.Goods[i].price) - parseFloat(that.data.Goods[i].integral_price))* 100)/ 100;
                  // that.data.Goods[i].integral_price = temp;
                } else {
                  var price = 0.00;
                  var temp = that.data.Goods[i].price;
                  list.push(price);
                  list1.push(temp);
                  // that.data.Goods[i].price = 0.00;
                  // that.data.Goods[i].integral_price = that.data.Goods[i].price;
                }
              }

              that.setData({
                priceList: list,
                integralpriceList: list1
              });
              console.log("============================-----------------------");

              // 个人简介
              let Introduce = {
                type: 0
              }

              if (res.data.introduce != '' && res.data.introduce != null) {
                Introduce.type = 1
                Introduce.content = res.data.introduce
              }
              if (res.data.voice != '' && res.data.voice != null) {
                // console.log('voice')
                Introduce.type = 1
                Introduce.voice = res.data.voice
                Introduce.logo = res.data.logo
                Introduce.duration = res.data.length
                that.setData({
                  durations: Number(res.data.length)
                })
                innerAudioContext.src = res.data.voice
                // console.log(res.data.voice)
                innerAudioContext.onCanplay(() => {
                  // innerAudioContext.duration;
                  // Introduce.duration = innerAudioContext.duration
                })
              }
              if (res.data.flags.length > 0) {
                Introduce.flags = res.data.flags
              }
              that.setData({
                Introduce
              })

              // 视频
              let Video = {
                type: 0
              }
              if (res.data.video != '' && res.data.video != null) {
                Video.type = 1
                Video.src = res.data.video
                Video.img = res.data.video_img
              }
              that.setData({
                Video
              })

              // 我的图片
              let Photo = {
                type: 0
              }
              if (res.data.files.length > 0) {
                Photo.type = 1
                Photo.list = [...res.data.files]
              }
              // console.log(Photo)
              that.setData({
                Photo
              })

              that.setData({
                shareInfo: {
                  carte: CarteInfo,
                  share_id: app.globalData.userInfo.id,
                  share_img: CarteInfo.img.src
                }
              })
            }
          })

      } catch (error) {
        console.log(error)
      }
    } else {
      that.setData({
        TaskShow: 4
      })
    }

  },

  // 打开个人统计信息页
  showPerson: function(e) {
    // console.log(e)
    wx.switchTab({
      url: '/pages/person/person',
    })
  },

  // 更新收藏状态
  changeCollStatus: function(e) {

    const that = this
    const status = e.detail.button_status
    const carte_id = e.detail.carte_id
    let haveTap = this.data.haveTap

    if (haveTap == 1) {
      that.setData({
        haveTap: 0
      })
      if (that.data.CarteInfo.is_allow == 2) {
        wx.showToast({
          title: '默认门店帮扶系统！不可取消收藏',
          icon: 'none'
        })
        that.setData({
          haveTap: 1
        })
        // app.showTipMsg('默认名片！不可取消收藏')
      } else {
        try {
          app.HttpGetSend(
            update_coll_status, {
              status: status,
              collection_id: that.data.userInfo.id,
              uid: carte_id
            },
            function(res) {

              if (res === '-10000') {
                wx.hideTabBar()
                that.setData({
                  authSettingUser: 0
                });
              }
              if (res.msg != "success") {
                app.showTipMsg(res.msg);
              } else {
                let VotesList = [...that.data.VotesList]
                if (haveTap == 1) {
                  if (status == 0) {
                    VotesList[1].count = VotesList[1].count + 1
                    VotesList[1].status = 1
                    VotesList[1].icon = '../../images/ic_connection_collect_sel.png'

                    // 发送模板消息-名片新增收藏消息
                    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 4, '/radarPages/radarCenter/radarCenter', '', '', '', '')
                    app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 2, '')
                  } else {
                    VotesList[1].count = VotesList[1].count - 1
                    VotesList[1].status = 0
                    VotesList[1].icon = '../../images/ic_connection_collect_nor.png'
                  }
                  app.radarAdd(that.data.carte_id, 2, status, '', app.globalData.userInfo.logo)



                }
                that.setData({
                  VotesList,
                })
              }
              that.setData({
                haveTap: 1
              })
            })

        } catch (error) {
          // console.log(error)
          that.setData({
            haveTap: 1
          })
        }
      }
      // console.log(haveTap,that.data.haveTap)
    } else {
      console.log('屏蔽重复点击')
    }
  },

  // 更新点赞状态
  changeLikeStatus: function(e) {
    const that = this
    const status = e.detail.button_status
    const carte_id = e.detail.carte_id
    let haveTap = this.data.haveTap
    if (haveTap == 1) {
      that.setData({
        haveTap: 0
      })
      try {
        app.HttpGetSend(
          update_like_status, {
            status: status,
            point_uid: that.data.userInfo.id,
            uid: that.data.carte_id
          },
          function(res) {
            // console.log(res)
            if (res === '-10000') {
              wx.hideTabBar()
              that.setData({
                authSettingUser: 0
              });
            }
            if (res.msg != "success") {
              app.showTipMsg(res.msg);
            } else {
              let VotesList = [...that.data.VotesList]
              if (haveTap == 1) {
                if (status == 0) {
                  app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 1, '')
                  // 发送模板消息-作品被点赞通知
                  // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 5, '/radarPages/radarCenter/radarCenter', '您的名片被点赞', '', '', '')

                  VotesList[2].count = VotesList[2].count + 1
                  VotesList[2].status = 1
                  VotesList[2].icon = '../../images/ic_connection_praise_sel.png'

                } else {
                  VotesList[2].count = VotesList[2].count - 1
                  VotesList[2].status = 0
                  VotesList[2].icon = '../../images/ic_connection_praise_nor.png'
                }
                app.radarAdd(that.data.carte_id, 1, status, '', app.globalData.userInfo.logo)

              }
              that.setData({
                VotesList
              })

            }
            that.setData({
              haveTap: 1
            })
          })
      } catch (error) {
        console.log(error)
        that.setData({
          haveTap: 1
        })
      }
    } else {
      console.log('屏蔽重复点击')
    }
  },

  // 名片canvas渲染并打开分享遮罩层
  canvasAndShowshare: function(v) {
    const that = this
    var hide = that.data.TaskShow
    if (hide != 0) {
      that.setData({
        TaskShow: 0
      })
    }
    const CarteInfo = this.data.CarteInfo
    const userInfo = this.data.userInfo
    if (that.data.userInfo.id == CarteInfo.id && that.data.userInfo.type == 1) {
      app.showTipMsg('无权限');
      return false;
    }
    this.setData({
      video_show: false,
      haveTap: 0,
      haveShare: 0,
    })
    // wx.showLoading({
    //   mask: 'true'
    // })
    wx.hideTabBar()
    // wx.hideLoading()
    this.setData({
      haveTap: 1,
      haveShare: 1,
      TaskShow: 2,
      shareInfo: {
        carte: CarteInfo,
        share_id: userInfo.id,
        share_img: CarteInfo.img.src
      }
    })
    // that.renderCanvasCarte(CarteInfo).then(render_canvas_res => {
    //   // console.log(render_canvas_res)
    //   wx.hideTabBar()
    //   wx.hideLoading()
    //   that.setData({
    //     haveTap: 1,
    //     haveShare: 1,
    //     TaskShow: 2,
    //     shareInfo: {
    //       carte: CarteInfo,
    //       share_id: userInfo.id,
    //       share_img: render_canvas_res
    //     }
    //   })
    // })
  },

  // canvas渲染
  renderCanvasCarte: function(params) {
    const that = this
    // console.log(params)
    // const params = this.data.CarteList[idx]
    const wxGetImageInfo = function(src) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        wx.getImageInfo({
          src: src,
          success(res) {
            resolve(res)
          },
          fail(err) {
            reject(err)
          },
          complete() {

          }
        })
      })
      return p
    }
    const weGetElementInfo = function(filterArr) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        const query = wx.createSelectorQuery()
        filterArr.map(items => {
          if (items.type == 1) {
            return query.select(items.content).boundingClientRect()
          } else if (items.type == 2) {
            return query.selectAll(items.content).boundingClientRect()
          }
        })
        query.exec(result => {
          resolve(result)
        })
      })
      return p
    }
    const toTempPath = new Promise((resolve, reject) => {
      Promise.all([
        weGetElementInfo([{
            content: '.carte_mainBox',
            type: 1
          },
          {
            content: '.carte_mainBox .mainLeft .avatar',
            type: 1
          }, //用户形像照
          {
            content: '.carte_mainBox .mainLeft .avatarMask',
            type: 1
          }, //头像遮罩
          {
            content: '.carte_mainBox .mainRight .companyInfo .company',
            type: 1
          }, //公司名称
          {
            content: '.carte_mainBox .mainRight .companyInfo .logo',
            type: 1
          }, //公司logo
          {
            content: '.carte_mainBox .mainRight .positionInfo2 .job',
            type: 1
          }, //职位
          {
            content: '.carte_mainBox .mainRight .positionInfo2 .point',
            type: 1
          }, //点
          {
            content: '.carte_mainBox .mainRight .positionInfo .name',
            type: 1
          }, //名字
          {
            content: '.carte_mainBox .mainRight .phoneInfo .phone',
            type: 1
          }, //电话
          {
            content: '.carte_mainBox .mainRight .phoneInfo .icon',
            type: 1
          }, //电话Icon
          {
            content: '.carte_mainBox .mainRight .mailInfo .mail',
            type: 1
          }, //邮箱
          {
            content: '.carte_mainBox .mainRight .mailInfo .icon',
            type: 1
          }, //邮箱Icon
          {
            content: '.carte_mainBox .mainRight .addrInfo .addr',
            type: 1
          }, //地址
          {
            content: '.carte_mainBox .mainRight .addrInfo .icon',
            type: 1
          }, //地址Icon
        ]),
        wxGetImageInfo(params.img.src),
        wxGetImageInfo(params.comLogo.src),
      ]).then(res => {
        let topBorder = res[0][0].top
        let leftBorder = res[0][0].left
        let canvasWidth = res[0][0].width
        let canvasHeight = res[0][0].height
        let getPosition = (type, index) => {
          let aimTop = res[0][index].top - topBorder
          let aimLeft = res[0][index].left - leftBorder
          if (type == 0 || type == 3) {
            return [aimLeft, aimTop]
          } else if (type == 1) {
            return [res[0][index].width, res[0][index].height]
          } else if (type == 2) {
            return [aimLeft, aimTop, res[0][index].width, res[0][index].height]
          }
        }
        let roundRect = (ctx_ctx, x, y, w, h, r) => {
          ctx_ctx.save()

          // 开始绘制
          ctx_ctx.beginPath()
          // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
          // 这里是使用 fill 还是 stroke都可以，二选一即可
          ctx_ctx.setFillStyle('transparent')
          // ctx_ctx.setStrokeStyle('transparent')
          // 左上角
          ctx_ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

          // border-top
          ctx_ctx.moveTo(x + r, y)
          ctx_ctx.lineTo(x + w - r, y)
          ctx_ctx.lineTo(x + w, y + r)
          // 右上角
          ctx_ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

          // border-right
          ctx_ctx.lineTo(x + w, y + h - r)
          ctx_ctx.lineTo(x + w - r, y + h)
          // 右下角
          ctx_ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

          // border-bottom
          ctx_ctx.lineTo(x + r, y + h)
          ctx_ctx.lineTo(x, y + h - r)
          // 左下角
          ctx_ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

          // border-left
          ctx_ctx.lineTo(x, y + r)
          ctx_ctx.lineTo(x + r, y)

          // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
          ctx_ctx.fill()
          // ctx_ctx.stroke()
          ctx_ctx.closePath()
          // 剪切
          ctx_ctx.clip()

          ctx_ctx.restore()
        }
        const ctx = wx.createCanvasContext('carte_canvas')

        // 白色背景
        ctx.rect(0, 0, canvasWidth, canvasHeight)
        ctx.setFillStyle('white')
        ctx.fill()

        // roundRect(ctx,0,0,canvasWidth,canvasHeight,10)

        // 个人形象照
        ctx.drawImage(res[1].path, ...getPosition(2, 1))

        // 形象照遮挡
        ctx.drawImage('../../images/carteShow/avatar_fg.png', ...getPosition(2, 2))

        // 公司名称
        ctx.setFontSize(11)
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        ctx.fillText(params.comName.content, ...getPosition(0, 3))

        // 公司LOGO
        ctx.drawImage(res[2].path, ...getPosition(2, 4))

        // 职位
        ctx.setFontSize(12)
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        ctx.fillText(params.position.content, ...getPosition(0, 5))

        // 点
        // console.log(...getPosition(2, 6))
        ctx.beginPath()
        ctx.rect(...getPosition(2, 6))
        ctx.setFillStyle('#333')
        ctx.fill()

        // 名字
        ctx.setFontSize(24)
        ctx.fillStyle = '#333';
        ctx.fillText(params.name.content, ...getPosition(0, 7))

        // 电话
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.mobile.content, ...getPosition(0, 8))

        // 电话Icon
        ctx.drawImage('../../images/carteShow/phone.png', ...getPosition(2, 9))

        // 邮箱
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.email.content, ...getPosition(0, 10))

        // 邮箱Icon
        ctx.drawImage('../../images/carteShow/email.png', ...getPosition(2, 11))

        // 地址
        ctx.setFontSize(10)
        ctx.fillStyle = '#333';
        ctx.fillText(params.address.content, ...getPosition(0, 12))

        // 地址Icon
        ctx.drawImage('../../images/carteShow/addr.png', ...getPosition(2, 13))

        ctx.draw(false, function(canvas_res) {
          // console.log(canvas_res)
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 500,
            height: 400,
            destWidth: 500,
            destHeight: 400,
            canvasId: 'carte_canvas',
            success(canvas_temp_res) {
              // resolve(canvas_temp_res.tempFilePath)
              // console.log(canvas_temp_res)
              wx.uploadFile({
                url: baseUrl + ftp_share_image, // 仅为示例，非真实的接口地址
                filePath: canvas_temp_res.tempFilePath,
                name: 'file',
                formData: {},
                success(upload_res) {
                  // console.log(upload_res)
                  let json_upload_res = JSON.parse(upload_res.data)
                  // resolve(upload_res.data)
                  // console.log(json_upload_res)
                  if (json_upload_res.msg != "success") {
                    app.showTipMsg(res.msg)
                    reject()
                  } else {
                    resolve(json_upload_res.data)
                  }
                },
                fail(upload_err) {
                  // console.log(upload_err)
                  reject(upload_err)
                }
              })
            },
            fail(canvas_temp_err) {
              reject(canvas_temp_err)
            }
          })
        })
      })
    })
    return toTempPath
  },

  // 关闭分享遮罩层
  HideShareMask: function() {
    this.setData({
      TaskShow: 0,
      video_show: true
    })
    wx.showTabBar()
  },

  // 点击立即进入 关闭欢迎遮罩层
  hideWelcomeTask: function() {
    wx.showTabBar()
    this.setData({
      TaskShow: 0,
      issharecome: false
    })
  },

  showSharePost: function() {
    wx.showTabBar({

    });
    const that = this
    let CarteInfo = this.data.CarteInfo
    CarteInfo.img.src = CarteInfo.img.src.split('?x-oss-process=style/index_mp')[0];
    CarteInfo.comLogo.src = CarteInfo.comLogo.src.split('?x-oss-process=style/goods_skeletonize')[0];
    wx.navigateTo({
      url: '/pages/sharePost/sharePost?carte_info=' + encodeURIComponent(JSON.stringify(CarteInfo))
    })
  },

  // 保存联系人信息
  saveContacts: function() {
    const that = this
    let params = {
      firstName: that.data.CarteInfo.name.content,
      workPhoneNumber: that.data.CarteInfo.mobile.content
    }

    wx.addPhoneContact({
      ...params,
      success: function(res) {
        console.log('保存联系人信息成功:', res)
      },
      complete: function(res) {
        console.log('保存联系人信息结果:', res)
      }
    })
  },

  // 拨打电话
  makeCall: function(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.content // 仅为示例，并非真实的电话号码
    })
  },

  // 复制到剪贴板
  copyToCli: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.content,
      success(res) {
        app.showTipMsg('复制到剪贴板')
      }
    })
  },
  //跳转地图
  getLocation: function() {
    const latitude = Number(this.data.com_lat)
    const longitude = Number(this.data.com_lng)
    const name = this.data.address
    const address = this.data.address
    // const accuracy = res.accuracy
    // const scale = res.scale
    console.log(latitude);
    console.log(latitude);
    wx.openLocation({ //​使用微信内置地图查看位置。
      latitude,
      longitude,
      name: name,
      address: address,
      scale: 18,
      // accuracy,
    })
  },
  to_person: function() {
    this.setData({
      authSettingUser_task: true,
    });
    wx.navigateTo({
      url: '/shopPages/login/login',
    })
  },
  // 跳转购买名片页
  showBuyCarte: function() {
    if (app.globalData.authSettingUser > 0) {
      try {
        // ai添加纪录 对产品感兴趣
        app.aiAddRecord(2)
      } catch (error) {
        console.log(error)
      }

      // 雷达添加查看记录 -点击购买名片数
      app.radarAdd(app.globalData.SwitchTabParams.v_id, 14, '', '', app.globalData.userInfo.logo)

      // 发送模板消息-访客到访通知
      // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在购买名片', '', '', '')

      let CarteInfo = this.data.CarteInfo
      CarteInfo.img.src = CarteInfo.img.src.split('?x-oss-process=style/index_mp')[0];
      CarteInfo.comLogo.src = CarteInfo.comLogo.src.split('?x-oss-process=style/goods_skeletonize')[0];

      wx.navigateTo({
        url: '/pages/buyCarte/buyCarte?params=' + encodeURIComponent(JSON.stringify(this.data.CarteInfo))
      })

    } else {
      this.setData({
        authSettingUser_task: false
      });
    }

  },

  // 开始播放录音
  startPlay: function() {
    const that = this
    let Introduce = JSON.parse(JSON.stringify(this.data.Introduce))
    // console.log(innerAudioContext.src)
    app.radarAdd(that.data.carte_id, 10, '', '', app.globalData.userInfo.logo)
    app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 10, '')
    // 发送模板消息-访客到访通知
    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在播放录音', '', '', '')

    innerAudioContext.play()
    innerAudioContext.onPlay(res => {
      Introduce.type = 2
      that.setData({
        playStatus: true
      })
      that.setData({
        Introduce
      })
      console.log('recorder play start')
    })

    innerAudioContext.onEnded(res => {
      console.log('recorder onEnded start')
      Introduce.type = 1
      that.setData({
        Introduce
      })
      that.setData({
        playStatus: false
      })
    })

  },

  // 结束播放录音
  stopPlay: function() {
    const that = this
    let Introduce = JSON.parse(JSON.stringify(this.data.Introduce))
    innerAudioContext.stop()
    innerAudioContext.onStop(res => {
      Introduce.type = 1
      that.setData({
        Introduce
      })
      that.setData({
        playStatus: false
      })
      console.log('tap stop')
    })
  },

  // 切换标签点赞状态
  changeFlagLikeStatus: function(e) {
    // console.log(e)
    const that = this
    const index = e.currentTarget.dataset.idx
    const haveTap = this.data.haveTap
    const Introduce = JSON.parse(JSON.stringify(that.data.Introduce))
    if (haveTap == 1) {
      that.setData({
        haveTap: 0
      })
      app.HttpGetSend(
        update_flag_like_status, {
          uid: e.currentTarget.dataset.uid,
          point_uid: app.globalData.userInfo.id,
          flag_id: e.currentTarget.dataset.flagid,
          status: Introduce.flags[index].is_point
        },
        function(res) {
          // console.log(res)
          if (res === '-10000') {
            wx.hideTabBar()
            that.setData({
              authSettingUser: 0
            });
          }
          if (res.msg != "success") {
            app.showTipMsg(res.msg);
          } else {
            let changed = {}
            if (Introduce.flags[index].is_point == 1) {

              changed['Introduce.flags[' + index + '].point_num'] = Introduce.flags[index].point_num - 1
              changed['Introduce.flags[' + index + '].is_point'] = null
            } else {
              changed['Introduce.flags[' + index + '].point_num'] = Introduce.flags[index].point_num + 1
              changed['Introduce.flags[' + index + '].is_point'] = 1
            }
            changed['haveTap'] = 1
            that.setData(changed)
          }
        })
    } else {
      console.log('屏蔽重复点击')
    }
  },
  startPlayVideo1: function() {
    this.setData({
      video1_show: false
    });
  },
  bindended1: function() {
    this.setData({
      video1_show: true
    });
  },
  // 视频开始播放
  startPlayVideo: function() {
    var that = this
    app.radarAdd(this.data.carte_id, 9, '', '', app.globalData.userInfo.logo)
    app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 2, '')
    // 发送模板消息-访客到访通知
    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '正在播放视频', '', '', '')
  },

  // 全屏展示图片
  showPicture: function(e) {
    // console.log(e)
    let img_src = e.currentTarget.dataset.src
    wx.previewImage({
      current: img_src, // 当前显示图片的http链接
      urls: [img_src] // 需要预览的图片http链接列表
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  renderCarte: function(params) {
    const that = this
    // let
  },


  //分享弹窗

  fxmodeShow() {
    this.setData({
      fx_mode: !this.data.fx_mode
    });
    if (this.data.fx_mode) {
      wx.hideTabBar({

      });
    } else {
      wx.showTabBar({

      });
    }


  },

  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function(e) {
    const that = this
    const shareInfo = that.data.shareInfo
    const carte = that.data.shareInfo.carte
    app.radarAdd(carte.id, 3, '', '', app.globalData.userInfo.logo)
    if (app.globalData.userInfo.id != app.globalData.SwitchTabParams.v_id) {
      // 发送模板消息-访客到访通知
      app.addlog(app.globalData.SwitchTabParams.v_id, that.data.fangwname, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 3, '')
    }
    // console.log('首页radarAdd转发:', carte.id);
    console.log(shareInfo);
    // 发送模板消息-作品被转发通知
    app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 2, '/radarPages/radarCenter/radarCenter?coming_status=1', '您的人脉资料被' + app.globalData.userInfo.username + '转发了', '', '', '')
    if (e.from === 'button') {
      // 来自页面内转发按钮
      showShareStatus = 1;
    }
    if (that.data.content.indexOf("**") != -1) {
      var sharecontent = that.data.content.replace('**', carte.name.content);
    } else {
      sharecontent = that.data.content;
    }
    console.log(carte.id);
    console.log(shareInfo.share_id);
    return {
      title: sharecontent,
      path: '/pages/carteShow/carteShow?carte_id=' + carte.id + '&share_id=' + shareInfo.share_id,
      complete(res) {
        that.setData({
          haveTap: 1,
          TaskShow: 0,
          fxTaskShow: 1
        })

        // 发送模板消息-作品被转发通知
        app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 2, '/radarPages/radarCenter/radarCenter?coming_status=1', '转发了人脉资料', '', '', '')

        wx.showTabBar()
      }
    }

  }
})